<?php

// no direct access
defined('_JEXEC') or die('Restricted access');

/*
 * Make sure the user is authorized to view this page
 */
$user = & JFactory::getUser();
if (!$user->authorize('com_hotel', 'manage')) {
    //$mainframe->redirect( 'index.php', JText::_('ALERTNOTAUTH') );
}

require_once( JApplicationHelper::getPath('admin_html') );
// Set the table directory
JTable::addIncludePath(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_hotel' . DS . 'tables');

$task = JRequest::getCmd('task');
$task2 = JRequest::getCmd('task2');
$view = JRequest::getCmd('view');
//print_r($view);
//die;
$id = JRequest::getVar('id', 0, 'get', 'int');
$id_ocupacao = JRequest::getVar('idOcupacao', 0, 'post', 'int');
$num_ap = JRequest::getVar('num', 0, 'post', 'int');
$cid = JRequest::getVar('cid', array(0), 'post', 'array');
JArrayHelper::toInteger($cid, array(0));
//print_r($_POST);
//print_r($task);
       // die;
switch ($task) {

    case 'add' :
        
        eval("edit" . $view . "($option);");
        break;

    case 'edit':
        
        eval("edit" . $view . "($option);");
        break;

    case 'apply':
    case 'save':

    case 'save2new':
    case 'save2copy':
        if($_POST['task2']=="saveConta"){
            saveConta($task);
            break;
        }


        eval("save" . $view . "($task);");
        break;
    case 'saveConta':
         saveConta($task);
        break;
    case 'remove':
        if ($id_ocupacao != 0) {
            eval("remove" . $view . "(\$cid,\$id_ocupacao,\$num_ap);");
        } else {
            eval("remove" . $view . "(\$cid);");
        }
        break;

    case 'publish':
        changeHotel($cid, 1);
        break;

    case 'unpublish':
        changeHotel($cid, 0);
        break;

    case 'orderup':
        orderHotels($cid[0], -1);
        break;

    case 'orderdown':
        orderHotels($cid[0], 1);
        break;

    case 'accesspublic':
        changeAccess($cid[0], 0);
        break;

    case 'accessregistered':
        changeAccess($cid[0], 1);
        break;

    case 'accessspecial':
        changeAccess($cid[0], 2);
        break;

    case 'saveorder':
        saveOrder($cid);
        break;

    case 'cancel':
        if ($num_ap != 0) {
            eval("cancel" . $view . "(\$num_ap);");
        } else {
            eval("cancel" . $view . "();");
        }
        break;

    default:
        switch ($view) {
            case 'consumiveis' :
                showConsumiveis($option);
                break;
            case 'ocupacoes':
                showOcupacoes($option);
                break;
            case 'reservas':
                showReservas($option);
                break;
            case 'apartamentos':
                showApartamentos($option);
                break;
            case 'despesas':
                $num = JRequest::getVar('num', 0, 'get', 'int');
                showDespesas($option, $num,$task);
                break;
        }
        //showHotels( $option );
        break;
}

/**
 * List the records
 * @param string The current GET/POST option
 */
function showConsumiveis($option) {
    global $mainframe;
    //print_r('lokoS');
    //die;
    $db = & JFactory::getDBO();
    $filter_state = $mainframe->getUserStateFromRequest($option . 'filter_state', 'filter_state', '', 'word');
    $filter_catid = $mainframe->getUserStateFromRequest($option . 'filter_catid', 'filter_catid', 0, 'int');
    $search = $mainframe->getUserStateFromRequest($option . 'search', 'search', '', 'string');
    if (strpos($search, '"') !== false) {
        $search = str_replace(array('=', '<'), '', $search);
    }
    $search = JString::strtolower($search);

    $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
    $limitstart = $mainframe->getUserStateFromRequest($option . '.limitstart', 'limitstart', 0, 'int');

    $where = array();

    if ($search) {
        $where[] = 'cd.descricao LIKE ' . $db->Quote('%' . $db->getEscaped($search, true) . '%', false);
    }

    if ($filter_state) {
        if ($filter_state == 'P') {
            $where[] = 'cd.tipo = \'P\'';
        } else if ($filter_state == 'S') {
            $where[] = 'cd.tipo = \'S\'';
        }
    }

    $where = ( count($where) ? ' WHERE ' . implode(' AND ', $where) : '' );


    // get the total number of records
    $query = 'SELECT COUNT(*)'
            . ' FROM consumiveis AS cd'
            . $where
    ;
    $db->setQuery($query);
    $total = $db->loadResult();

    jimport('joomla.html.pagination');
    $pageNav = new JPagination($total, $limitstart, $limit);

    // get the subset (based on limits) of required records
    $query = 'SELECT cd.*'
            . ' FROM consumiveis AS cd'
            . $where
            . $orderby
    ;
    $db->setQuery($query, $pageNav->limitstart, $pageNav->limit);
    $rows = $db->loadObjectList();

    // build list of categories
    $javascript = 'onchange="document.adminForm.submit();"';
    //$lists['catid'] = JHTML::_('list.category',  'filter_catid', 'com_hotel_details', intval( $filter_catid ), $javascript );
    // state filter
    $lists['state'] = JHTML::_('grid.tipoCons', $filter_state);

    // search filter
    $lists['search'] = $search;

    HTML_hotel::showConsumiveis($rows, $pageNav, $option, $lists);
}

function showOcupacoes($option) {
    global $mainframe;
    //print_r('lokoS');
    //die;
    $db = & JFactory::getDBO();
    $filter_state = $mainframe->getUserStateFromRequest($option . 'filter_state', 'filter_state', '', 'word');
    $filter_catid = $mainframe->getUserStateFromRequest($option . 'filter_catid', 'filter_catid', 0, 'int');
    $search = $mainframe->getUserStateFromRequest($option . 'search', 'search', '', 'string');
    if (strpos($search, '"') !== false) {
        $search = str_replace(array('=', '<'), '', $search);
    }
    $search = JString::strtolower($search);

    $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
    $limitstart = $mainframe->getUserStateFromRequest($option . '.limitstart', 'limitstart', 0, 'int');

    $where = array();

    if ($search) {
        $where[] = 'cd.descricao LIKE ' . $db->Quote('%' . $db->getEscaped($search, true) . '%', false);
    }
    if ($filter_catid) {
        $where[] = 'cd.catid = ' . (int) $filter_catid;
    }
    if ($filter_state) {
        if ($filter_state == 'P') {
            $where[] = 'cd.tipo = P';
        } else if ($filter_state == 'U') {
            $where[] = 'cd.published = S';
        }
    }

    //$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
    //$where = " WHERE dataSaida is null";
    // get the total number of records
    $query = 'SELECT COUNT(*)'
            . ' FROM ocupacao AS cd'

    ;
    $db->setQuery($query);
    $total = $db->loadResult();

    jimport('joomla.html.pagination');
    $pageNav = new JPagination($total, $limitstart, $limit);

    // get the subset (based on limits) of required records
    $query = 'SELECT oc.*,c.name'
            . ' FROM ocupacao AS oc INNER JOIN #__users as c ON oc.cliente=c.id'
            . $orderby
    ;
    $db->setQuery($query, $pageNav->limitstart, $pageNav->limit);
    $rows = $db->loadObjectList();

    // build list of categories
    $javascript = 'onchange="document.adminForm.submit();"';
    //$lists['catid'] = JHTML::_('list.category',  'filter_catid', 'com_hotel_details', intval( $filter_catid ), $javascript );
    // state filter
    $lists['state'] = JHTML::_('grid.state', $filter_state);

    // search filter
    $lists['search'] = $search;

    HTML_hotel::showOcupacoes($rows, $pageNav, $option, $lists);
}

function showReservas($option) {
    global $mainframe;

    $db = & JFactory::getDBO();
    $search = $mainframe->getUserStateFromRequest($option . 'search', 'search', '', 'string');
    if (strpos($search, '"') !== false) {
        $search = str_replace(array('=', '<'), '', $search);
    }
    $search = JString::strtolower($search);

    $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
    $limitstart = $mainframe->getUserStateFromRequest($option . '.limitstart', 'limitstart', 0, 'int');

    $where = array();

    if ($search) {
        $where[] = 'c.name LIKE ' . $db->Quote('%' . $db->getEscaped($search, true) . '%', false);
    }


    //$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
    //$where = " WHERE dataSaida is null";
    // get the total number of records
    $query = 'SELECT COUNT(*)'
            . ' FROM reserva AS re'

    ;
    $db->setQuery($query);
    $total = $db->loadResult();

    jimport('joomla.html.pagination');
    $pageNav = new JPagination($total, $limitstart, $limit);

    // get the subset (based on limits) of required records
    $query = 'SELECT re.*,c.name'
            . ' FROM reserva AS re INNER JOIN #__users as c ON re.cliente=c.id'
            . $orderby
    ;
    //print_r($query);
    //die;
    $db->setQuery($query, $pageNav->limitstart, $pageNav->limit);
    $rows = $db->loadObjectList();

    // build list of categories
    $javascript = 'onchange="document.adminForm.submit();"';
    //$lists['catid'] = JHTML::_('list.category',  'filter_catid', 'com_hotel_details', intval( $filter_catid ), $javascript );
    // state filter
    $lists['state'] = JHTML::_('grid.state', $filter_state);

    // search filter
    $lists['search'] = $search;

    HTML_hotel::showReservas($rows, $pageNav, $option, $lists);
}

function showApartamentos($option) {
    global $mainframe;
    
    $db = & JFactory::getDBO();
    $filter_state = $mainframe->getUserStateFromRequest($option . 'filter_state', 'filter_state', '', 'word');
    $filter_catid = $mainframe->getUserStateFromRequest($option . 'filter_catid', 'filter_catid', 0, 'int');
    $search = $mainframe->getUserStateFromRequest($option . 'search', 'search', '', 'string');
    if (strpos($search, '"') !== false) {
        $search = str_replace(array('=', '<'), '', $search);
    }
    $search = JString::strtolower($search);

    $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
    $limitstart = $mainframe->getUserStateFromRequest($option . '.limitstart', 'limitstart', 0, 'int');

    $where = array();

    if ($search) {
        $where[] = 'ap.num LIKE ' . $db->Quote('%' . $db->getEscaped($search, true) . '%', false);
    }
    if ($filter_catid) {
        $where[] = 'ap.tipo = ' . (int) $filter_catid;
    }
    if ($filter_state) {
        if ($filter_state == 'P') {
            $where[] = 'ap.ocupado = 1';
        } else if ($filter_state == 'U') {
            $where[] = 'ap.ocupado = 0';
        }
    }

    //$where 		= ( count( $where ) ? ' WHERE ' . implode( ' AND ', $where ) : '' );
    //$where = " WHERE dataSaida is null";
    // get the total number of records
    $query = 'SELECT COUNT(*)'
            . ' FROM apto AS ap'

    ;
    $db->setQuery($query);
    $total = $db->loadResult();

    jimport('joomla.html.pagination');
    $pageNav = new JPagination($total, $limitstart, $limit);

    // get the subset (based on limits) of required records
    $query = 'SELECT ap.*'
            . ' FROM apto AS ap '
            . $orderby
    ;
    $db->setQuery($query, $pageNav->limitstart, $pageNav->limit);
    $rows = $db->loadObjectList();

    // build list of categories
    $javascript = 'onchange="document.adminForm.submit();"';
    //$lists['catid'] = JHTML::_('list.category',  'filter_catid', 'com_hotel_details', intval( $filter_catid ), $javascript );
    // state filter
    $lists['state'] = JHTML::_('grid.state', $filter_state);

    // search filter
    $lists['search'] = $search;

    HTML_hotel::showApartamentos($rows, $pageNav, $option, $lists);
}

/**
 * Creates a new or edits and existing user record
 * @param int The id of the record, 0 if a new entry
 * @param string The current GET/POST option
 */
function showDespesas($option, $num,$task) {
    global $mainframe;

    
    $db = & JFactory::getDBO();
    $filter_state = $mainframe->getUserStateFromRequest($option . 'filter_state', 'filter_state', '', 'word');
    $filter_catid = $mainframe->getUserStateFromRequest($option . 'filter_catid', 'filter_catid', 0, 'int');
    $search = $mainframe->getUserStateFromRequest($option . 'search', 'search', '', 'string');
    if (strpos($search, '"') !== false) {
        $search = str_replace(array('=', '<'), '', $search);
    }
    $search = JString::strtolower($search);

    $limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
    $limitstart = $mainframe->getUserStateFromRequest($option . '.limitstart', 'limitstart', 0, 'int');

    $where = array();

    if ($search) {
        $where[] = 'cd.descricao LIKE ' . $db->Quote('%' . $db->getEscaped($search, true) . '%', false);
    }

    if ($filter_state) {
        if ($filter_state == 'P') {
            $where[] = 'cd.tipo = \'P\'';
        } else if ($filter_state == 'S') {
            $where[] = 'cd.tipo = \'S\'';
        }
    }

    $where = ( count($where) ? ' WHERE ' . implode(' AND ', $where) : '' );


    // get the total number of records
    $query = 'SELECT *
                    FROM conta_consumiveis AS cc
                    INNER JOIN consumiveis AS c ON cc.id_consumiveis = c.id
                    INNER JOIN ocupacao AS o ON o.id = cc.id_ocupacao
                    WHERE o.numApto =' . $num .
            'AND o.id = (
                    SELECT max( id )
                    FROM ocupacao
                    WHERE numApto =' . $num . ' )';

    $db->setQuery($query);
    $total = $db->loadResult();

    jimport('joomla.html.pagination');
    $pageNav = new JPagination($total, $limitstart, $limit);

    // get the subset (based on limits) of required records
    $query ="SELECT max( id )
                    FROM ocupacao
                    WHERE numApto =" . $num;
    $db->setQuery($query);
    $idOcupacao = $db->loadResult();
    // print_r($idOcupacao);
   //die;

    $query = "SELECT o.id ,c.id as 'id_consumiveis', c.descricao as 'desc',c.tipo as 'tipo',c.valor as 'valor', o.dataEntrada, o.dataSaida, o.cliente, o.qtdePessoas, cc.data
                    FROM conta_consumiveis AS cc
                    INNER JOIN consumiveis AS c ON cc.id_consumiveis = c.id
                    INNER JOIN ocupacao AS o ON o.id = cc.id_ocupacao
                    WHERE o.numApto =" . $num .
            " AND o.id = (
                    SELECT max( id )
                    FROM ocupacao
                    WHERE numApto =" . $num . " )"
            . $orderby
    ;
    //print_r($query);
    //die;
    $db->setQuery($query, $pageNav->limitstart, $pageNav->limit);
    $rows = $db->loadObjectList();
    

    // build list of categories
    $javascript = 'onchange="document.adminForm.submit();"';
    $lists['state'] = JHTML::_('grid.tipoCons', $filter_state);

    // search filter
    $lists['search'] = $search;

    if($task=="fecharConta"){
        
       HTML_hotel::editConta($rows, $option, $lists, $idOcupacao);
       return;
    }

    HTML_hotel::showDespesas($rows, $pageNav, $option, $lists, $idOcupacao);
}

function editConsumiveis($edit) {
    //print_r("entrou");
    //die;
    $db = & JFactory::getDBO();
    $user = & JFactory::getUser();

    $cid = JRequest::getVar('cid', array(0), '', 'array');
    $option = JRequest::getCmd('option');

    JArrayHelper::toInteger($cid, array(0));

    $row = & JTable::getInstance('consumiveis', 'Table');
    // load the row from the db table
    if ($edit)
        $row->load($cid[0]);
    //print_r($row);
    //die;
    if ($edit) {
        // do stuff for existing records
        $row->checkout($user->get('id'));
    } else {
        // do stuff for new records
        $row->imagepos = 'top';
        $row->ordering = 0;
        $row->published = 1;
    }
    $lists = array();


    // get params definitions
    $file = JPATH_ADMINISTRATOR . '/components/com_hotel/hotel_items.xml';
    $params = new JParameter($row->params, $file, 'component');


    HTML_hotel::editConsumiveis($row, $lists, $option, $params);
}

function editOcupacoes($edit) {
    //print_r("entrou");
    //die;
    $db = & JFactory::getDBO();
    $user = & JFactory::getUser();

    $cid = JRequest::getVar('cid', array(0), '', 'array');
    $option = JRequest::getCmd('option');

    JArrayHelper::toInteger($cid, array(0));

    $row = & JTable::getInstance('ocupacao', 'Table');
    // load the row from the db table
    if ($edit)
        $row->load($cid[0]);
    //print_r($row);
    //die;
    if ($edit) {
        // do stuff for existing records
        $row->checkout($user->get('id'));
    } else {
        // do stuff for new records
        $row->imagepos = 'top';
        $row->ordering = 0;
        $row->published = 1;
    }
    $lists = array();


    // get params definitions
    $file = JPATH_ADMINISTRATOR . '/components/com_hotel/hotel_items.xml';
    $params = new JParameter($row->params, $file, 'component');
    $clientlist[] = JHTML::_('select.option', '0', JText::_('Escolha um Cliente'), 'id', 'cliente');


    $sql = 'SELECT id as id, name as cliente'
            . ' FROM #__users WHERE usertype="Cliente"'
    ;

    $db->setQuery($sql);
    $clientes = $db->loadResult();
    $clientlist = array_merge($clientlist, $db->loadObjectList());

    $lists['clientes'] = JHTML::_('select.genericlist', $clientlist, 'cliente', 'class="inputbox" size="1"', 'id', 'cliente', $row->cliente);


    HTML_hotel::editOcupacoes($row, $lists, $option, $params);
}

function editReservas($edit) {
    //print_r("entrou");
    //die;
    $db = & JFactory::getDBO();
    $user = & JFactory::getUser();

    $cid = JRequest::getVar('cid', array(0), '', 'array');
    $option = JRequest::getCmd('option');

    JArrayHelper::toInteger($cid, array(0));

    $row = & JTable::getInstance('reserva', 'Table');
    // load the row from the db table
    if ($edit)
        $row->load($cid[0]);
    //print_r($row);
    //die;
    if ($edit) {
        // do stuff for existing records
        $row->checkout($user->get('id'));
    } else {
        // do stuff for new records
        $row->imagepos = 'top';
        $row->ordering = 0;
        $row->published = 1;
    }
    $lists = array();

    $clientlist[] = JHTML::_('select.option', '0', JText::_('Escolha um Cliente'), 'id', 'cliente');


    $sql = 'SELECT id as id, name as cliente'
            . ' FROM #__users WHERE usertype="Cliente"'
    ;

    $db->setQuery($sql);
    $clientes = $db->loadResult();
    $clientlist = array_merge($clientlist, $db->loadObjectList());

    $lists['clientes'] = JHTML::_('select.genericlist', $clientlist, 'cliente', 'class="inputbox" size="1"', 'id', 'cliente', $row->cliente);


    // get params definitions
    $file = JPATH_ADMINISTRATOR . '/components/com_hotel/hotel_items.xml';
    $params = new JParameter($row->params, $file, 'component');


    HTML_hotel::editReservas($row, $lists, $option, $params);
}

function editApartamentos($edit) {
    //print_r("entrou");
    //die;
    $db = & JFactory::getDBO();
    $user = & JFactory::getUser();

    $cid = JRequest::getVar('cid', array(0), '', 'array');
    $option = JRequest::getCmd('option');

    JArrayHelper::toInteger($cid, array(0));

    $row = & JTable::getInstance('apto', 'Table');
    // load the row from the db table
    if ($edit)
        $row->load($cid[0]);
    //print_r($cid);
    // die;
    if ($edit) {
        // do stuff for existing records
        $row->checkout($user->get('id'));
    } else {
        // do stuff for new records
        $row->imagepos = 'top';
        $row->ordering = 0;
        $row->published = 1;
    }
    $lists = array();



    // get params definitions
    $file = JPATH_ADMINISTRATOR . '/components/com_hotel/hotel_items.xml';
    $params = new JParameter($row->params, $file, 'component');
//print_r($row);
    // die;
    HTML_hotel::editApartamentos($row, $lists, $option, $params);
}

function editDespesas($edit) {
    //print_r($_REQUEST);
    //die;
    $db = & JFactory::getDBO();
    $conslist[] = JHTML::_('select.option', '0', JText::_('Escolha um Consumivel'), 'id', 'descricao');

    $option = JRequest::getCmd('option');
    $sql = "SELECT id, descricao"
            . " FROM consumiveis "
    ;

    $db->setQuery($sql);
    //$clientes = $db->loadResult();
    $conslist = array_merge($conslist, $db->loadObjectList());

    $consumiveis = JHTML::_('select.genericlist', $conslist, 'consumiveis', 'class="inputbox" size="1"', 'id', 'descricao', '0');



    $idOcupacao = JRequest::getVar('idOcupacao');
    $numApto = JRequest::getCmd('num');
    HTML_hotel::editDespesa($numApto, $idOcupacao, $consumiveis, $option);
}

/**
 * Saves the record from an edit form submit
 * @param string The current GET/POST option
 */
function saveConsumiveis($task) {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    $row = & JTable::getInstance('consumiveis', 'Table');
    $post = JRequest::get('post');
    $post['misc'] = JRequest::getVar('misc', '', 'POST', 'string', JREQUEST_ALLOWHTML);
    if (!$row->bind($post)) {
        JError::raiseError(500, $row->getError());
    }
    // save params
    // save to a copy, reset the primary key
    if ($task == 'save2copy') {
        $row->id = 0;
    }

    // pre-save checks
    if (!$row->check()) {
        JError::raiseError(500, $row->getError());
    }



    // save the changes
    if (!$row->store()) {
        JError::raiseError(500, $row->getError());
    }
    $row->checkin();


    switch ($task) {
        case 'apply':
        case 'save2copy':
            $msg = JText::sprintf('Gravado com sucesso!', JText::_('Hotel'));
            $link = 'index.php?option=com_hotel&task=edit&cid[]=' . $row->id . '&view=consumiveis';
            break;

        case 'save2new':
            $msg = JText::sprintf('Gravado com sucesso!', JText::_('Hotel'));
            $link = 'index.php?option=com_hotel&task=edit&view=consumiveis';
            break;

        case 'save':
        default:
            $msg = JText::_('Gravado com sucesso!');
            $link = 'index.php?option=com_hotel&view=consumiveis';
            break;
    }

    $mainframe->redirect($link, $msg);
}

function saveOcupacoes($task) {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    $row = & JTable::getInstance('ocupacao', 'Table');
    $post = JRequest::get('post');

    $post['misc'] = JRequest::getVar('misc', '', 'POST', 'string', JREQUEST_ALLOWHTML);
    if (!$row->bind($post)) {
        JError::raiseError(500, $row->getError());
    }
    // save params
    // save to a copy, reset the primary key
    if ($task == 'save2copy') {
        $row->id = 0;
    }

    // pre-save checks
    if (!$row->check()) {
        JError::raiseError(500, $row->getError());
    }



    // save the changes
    $sql="SELECT ocupado from apto WHERE num=".$row->numApto;
    $db->setQuery( $sql );
    $ocupado = $db->loadResult();

    if($ocupado == 1){
         $link = 'index.php?option=com_hotel&task=edit&view=ocupacoes';
         $mainframe->redirect($link,"Apartamento encontra-se ocupado!");
        
    }

    if (!$row->store()) {
        JError::raiseError(500, $row->getError());
    }
    $row->checkin();
    $sql = "UPDATE apto SET ocupado = 1 WHERE num=" . $row->numApto;
    $db->setQuery($sql);
    $db->query();

    switch ($task) {
        case 'apply':
        case 'save2copy':
            $msg = JText::sprintf('Gravado com sucesso!', JText::_('Hotel'));
            $link = 'index.php?option=com_hotel&task=edit&cid[]=' . $row->id . '&view=ocupacoes';
            break;

        case 'save2new':
            $msg = JText::sprintf('Gravado com sucesso!', JText::_('Hotel'));
            $link = 'index.php?option=com_hotel&task=edit&view=ocupacoes';
            break;

        case 'save':
        default:
            $msg = JText::_('Gravado com sucesso!');
            $link = 'index.php?option=com_hotel&view=ocupacoes';
            break;
    }

    $mainframe->redirect($link, $msg);
}

function saveReservas($task) {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    $row = & JTable::getInstance('reserva', 'Table');
    $post = JRequest::get('post');
    //print_r($post);
    //die;

    $post['misc'] = JRequest::getVar('misc', '', 'POST', 'string', JREQUEST_ALLOWHTML);
    if (!$row->bind($post)) {
        JError::raiseError(500, $row->getError());
    }
    
    $sql = "select count(id)
        from reserva
        where numApto=" . $row->numapto . " and (( '". $row->dataEntrada ."'>=dataEntrada and '". $row->dataEntrada ."'<=dataSaida) or ('". $row->dataSaida ."'>=dataEntrada and '". $row->dataSaida ."'<=dataSaida))";
    $db->setQuery($sql);
    $reserva = $db->loadResult();

    $sql = "select count(id)
        from ocupacao
        where numApto=" . $row->numapto . " and (( '". $row->dataEntrada ."'>=dataEntrada and '". $row->dataEntrada ."'<=dataSaida) or ('". $row->dataSaida ."'>=dataEntrada and '". $row->dataSaida ."'<=dataSaida))";
    $db->setQuery($sql);
    $reserva1 = $db->loadResult();

    if($reserva!=0 || $reserva1!=0){

            $link = 'index.php?option=com_hotel&task=edit&cid[]=' . $row->id . '&view=reservas';
            $mainframe->redirect($link,"Reserva Indisponivel");
    }
     
    // save to a copy, reset the primary key
    if ($task == 'save2copy') {
        $row->id = 0;
    }

    // pre-save checks
    if (!$row->check()) {
        JError::raiseError(500, $row->getError());
    }



    // save the changes
    if (!$row->store()) {
        JError::raiseError(500, $row->getError());
    }
    $row->checkin();


    switch ($task) {
        case 'apply':
        case 'save2copy':
            $msg = JText::sprintf('Gravado com sucesso!', JText::_('Hotel'));
            $link = 'index.php?option=com_hotel&task=edit&cid[]=' . $row->id . '&view=reservas';
            break;

        case 'save2new':
            $msg = JText::sprintf('Gravado com sucesso!', JText::_('Hotel'));
            $link = 'index.php?option=com_hotel&task=edit&view=reservas';
            break;

        case 'save':
        default:
            $msg = JText::_('Gravado com sucesso!');
            $link = 'index.php?option=com_hotel&view=reservas';
            break;
    }

    $mainframe->redirect($link, $msg);
}

function saveApartamentos($task) {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    $row = & JTable::getInstance('apto', 'Table');
    $post = JRequest::get('post');
    //echo "<pre>";
    //print_r($post);


    $post['misc'] = JRequest::getVar('misc', '', 'POST', 'string', JREQUEST_ALLOWHTML);
    if (!$row->bind($post)) {
        JError::raiseError(500, $row->getError());
    }
    //echo "<pre>";
    // print_r($row);
    //die;
//$row->id=0;
    // save params
    // save to a copy, reset the primary key
    if ($task == 'save2copy') {
        $row->num = 0;
    }

    // pre-save checks
    /* if (!$row->check()) {
      JError::raiseError(500, $row->getError() );
      } */

    $sql = "INSERT INTO apto (num) VALUES (" . $row->num . ")";
    $db->setQuery($sql);
    $db->query();

    // save the changes
    if (!$row->store()) {
        JError::raiseError(500, $row->getError());
    }
    //$row->checkin();


    switch ($task) {
        case 'apply':
        case 'save2copy':
            $msg = JText::sprintf('Gravado com sucesso!', JText::_('Hotel'));
            $link = 'index.php?option=com_hotel&task=edit&cid[]=' . $row->num . '&view=apartamentos';
            break;

        case 'save2new':
            $msg = JText::sprintf('Gravado com sucesso!', JText::_('Hotel'));
            $link = 'index.php?option=com_hotel&task=edit&view=apartamentos';
            break;

        case 'save':
        default:
            $msg = JText::_('Gravado com sucesso manolo!');
            $link = 'index.php?option=com_hotel&view=apartamentos';
            break;
    }

    $mainframe->redirect($link, $msg);
}

function saveDespesas($task) {
    global $mainframe;
    $db = & JFactory::getDBO();
    JRequest::checkToken() or jexit('Invalid Token');

    $post = JRequest::get('post');

    $post['misc'] = JRequest::getVar('misc', '', 'POST', 'string', JREQUEST_ALLOWHTML);


    $sql = "INSERT INTO conta_consumiveis (id_ocupacao,id_consumiveis,data) VALUES (" . $post['id_ocupacao'] . "," . $post['consumiveis'] . ",NOW())";

    $db->setQuery($sql);
    $db->query();




    $msg = JText::_('Gravado com sucesso manolo!');
    $link = 'index.php?option=com_hotel&view=despesas&num=' . $post['num'];


    $mainframe->redirect($link, $msg);
}

function saveConta($task) {
    //die;
    global $mainframe;
    $db = & JFactory::getDBO();
    JRequest::checkToken() or jexit('Invalid Token');

    $post = JRequest::get('post');

    $post['misc'] = JRequest::getVar('misc', '', 'POST', 'string', JREQUEST_ALLOWHTML);


    $sql = "INSERT INTO conta (isPaga,formaPgto,id_ocupacao) VALUES (1," . $post['formaPgto'] . ",id_ocupacao)";

    $db->setQuery($sql);
    $db->query();

    $sql = "UPDATE apto SET ocupado=0 WHERE num=".$_POST['num'];

    $db->setQuery($sql);
    $db->query();



    $msg = JText::_('Gravado com sucesso!');
    $link = 'index.php?option=com_hotel&view=apartamentos';


    $mainframe->redirect($link, $msg);
}

/**
 * Removes records
 * @param array An array of id keys to remove
 * @param string The current GET/POST option
 */
function removeConsumiveis(&$cid) {       //print_r($cid);
////die;
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    JArrayHelper::toInteger($cid);

    if (count($cid)) {
        $cids = implode(',', $cid);
        $query = 'DELETE FROM consumiveis'
                . ' WHERE id IN ( ' . $cids . ' )'
        ;
        $db->setQuery($query);
        if (!$db->query()) {
            echo "<script> alert('" . $db->getErrorMsg(true) . "'); window.history.go(-1); </script>\n";
        }
    }

    $mainframe->redirect("index.php?option=com_hotel&view=consumiveis");
}

function removeOcupacoes(&$cid) {
    global $mainframe;


    JRequest::checkToken() or jexit('Invalid Token');


    $db = & JFactory::getDBO();
    JArrayHelper::toInteger($cid);

    if (count($cid)) {
        $cids = implode(',', $cid);
        $query = 'DELETE FROM ocupacao'
                . ' WHERE id IN ( ' . $cids . ' )'
        ;
        $db->setQuery($query);
        if (!$db->query()) {
            echo "<script> alert('" . $db->getErrorMsg(true) . "'); window.history.go(-1); </script>\n";
        }
    }

    $mainframe->redirect("index.php?option=com_hotel&view=ocupacoes");
}

function removeApartamentos(&$cid) {
    global $mainframe;


    JRequest::checkToken() or jexit('Invalid Token');


    $db = & JFactory::getDBO();
    JArrayHelper::toInteger($cid);

    if (count($cid)) {
        $cids = implode(',', $cid);
        $query = 'DELETE FROM apto'
                . ' WHERE num IN ( ' . $cids . ' )'
        ;
        $db->setQuery($query);
        if (!$db->query()) {
            echo "<script> alert('" . $db->getErrorMsg(true) . "'); window.history.go(-1); </script>\n";
        }
    }

    $mainframe->redirect("index.php?option=com_hotel&view=apartamentos");
}

function removeDespesas(&$cid, $id_ocupacao, $num) {
    global $mainframe;


    JRequest::checkToken() or jexit('Invalid Token');


    $db = & JFactory::getDBO();
    JArrayHelper::toInteger($cid);

    if (count($cid)) {
        $cids = implode(',', $cid);
        $query = 'DELETE FROM conta_consumiveis'
                . ' WHERE id_consumiveis IN ( ' . $cids . ' )'
                . ' AND id_ocupacao=' . $id_ocupacao
        ;

        $db->setQuery($query);
        if (!$db->query()) {
            echo "<script> alert('" . $db->getErrorMsg(true) . "'); window.history.go(-1); </script>\n";
        }
    }

    $mainframe->redirect("index.php?option=com_hotel&view=despesas&num=" . $num, "Estorno Realizado!");
}

function changeHotel($cid=null, $state=0) {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    $user = & JFactory::getUser();
    JArrayHelper::toInteger($cid);

    if (count($cid) < 1) {
        $action = $state ? 'publish' : 'unpublish';
        JError::raiseError(500, JText::_('Select an item to' . $action, true));
    }

    $cids = implode(',', $cid);

    $query = 'UPDATE #__hotel_details'
            . ' SET published = ' . (int) $state
            . ' WHERE id IN ( ' . $cids . ' )'
            . ' AND ( checked_out = 0 OR ( checked_out = ' . (int) $user->get('id') . ' ) )'
    ;
    $db->setQuery($query);
    if (!$db->query()) {
        JError::raiseError(500, $db->getErrorMsg());
    }

    if (count($cid) == 1) {
        $row = & JTable::getInstance('hotel', 'Table');
        $row->checkin(intval($cid[0]));
    }

    $mainframe->redirect('index.php?option=com_hotel');
}

/** JJC
 * Moves the order of a record
 * @param integer The increment to reorder by
 */
function orderHotels($uid, $inc) {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();

    $row = & JTable::getInstance('hotel', 'Table');
    $row->load($uid);
    $row->move($inc, 'catid = ' . (int) $row->catid . ' AND published != 0');

    $mainframe->redirect('index.php?option=com_hotel');
}

/** PT
 * Cancels editing and checks in the record
 */
function cancelHotel() {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    $row = & JTable::getInstance('hotel', 'Table');
    $row->bind(JRequest::get('post'));
    $row->checkin();

    $mainframe->redirect('index.php?option=com_hotel');
}

function cancelConsumiveis() {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    $row = & JTable::getInstance('consumiveis', 'Table');
    $row->bind(JRequest::get('post'));
    $row->checkin();

    $mainframe->redirect('index.php?option=com_hotel&view=consumiveis');
}

function cancelOcupacoes() {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    $row = & JTable::getInstance('ocupacao', 'Table');
    $row->bind(JRequest::get('post'));
    $row->checkin();

    $mainframe->redirect('index.php?option=com_hotel&view=ocupacoes');
}

function cancelReservas() {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    $row = & JTable::getInstance('reserva', 'Table');
    $row->bind(JRequest::get('post'));
    $row->checkin();

    $mainframe->redirect('index.php?option=com_hotel&view=reservas');
}

function cancelApartamentos() {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    $row = & JTable::getInstance('apto', 'Table');
    $row->bind(JRequest::get('post'));
    $row->checkin();

    $mainframe->redirect('index.php?option=com_hotel&view=apartamentos');
}

function cancelDespesas($apto) {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables


    $mainframe->redirect('index.php?option=com_hotel&view=despesas&num=' . $apto);
}

/**
 * changes the access level of a record
 * @param integer The increment to reorder by
 */
function changeAccess($id, $access) {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();

    $row = & JTable::getInstance('hotel', 'Table');
    $row->load($id);
    $row->access = $access;

    if (!$row->check()) {
        return $row->getError();
    }
    if (!$row->store()) {
        return $row->getError();
    }

    $mainframe->redirect('index.php?option=com_hotel');
}

function saveOrder(&$cid) {
    global $mainframe;

    // Check for request forgeries
    JRequest::checkToken() or jexit('Invalid Token');

    // Initialize variables
    $db = & JFactory::getDBO();
    $total = count($cid);
    $order = JRequest::getVar('order', array(0), 'post', 'array');
    JArrayHelper::toInteger($order, array(0));

    $row = & JTable::getInstance('hotel', 'Table');
    $groupings = array();

    // update ordering values
    for ($i = 0; $i < $total; $i++) {
        $row->load((int) $cid[$i]);
        // track categories
        $groupings[] = $row->catid;

        if ($row->ordering != $order[$i]) {
            $row->ordering = $order[$i];
            if (!$row->store()) {
                JError::raiseError(500, $db->getErrorMsg());
            }
        }
    }

    // execute updateOrder for each parent group
    $groupings = array_unique($groupings);
    foreach ($groupings as $group) {
        $row->reorder('catid = ' . (int) $group);
    }

    $msg = 'New ordering saved';
    $mainframe->redirect('index.php?option=com_hotel', $msg);
}
